﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Json;
using Wy.JiZhangSoft.Dictionaries;

namespace Wy.JiZhangSoft.Holidays
{
    public class HolidayAppService:JiZhangSoftAppService
    {
        private readonly IRepository<Dictionary> _dictionaries;
        private readonly IRepository<Holiday> _holidays;
        private readonly IJsonSerializer _jsonSerializer;

        public HolidayAppService(IRepository<Dictionary> dictionaries,
            IRepository<Holiday> holidays,
            IJsonSerializer jsonSerializer)
        {
            this._dictionaries = dictionaries;
            this._holidays = holidays;
            this._jsonSerializer = jsonSerializer;
        }

        /// <summary>
        /// 获取今天的节日数据
        /// </summary>
        public async Task<string> GetAsync(string date)
        {
            var holiday = await _holidays.SingleOrDefaultAsync(x => x.Date == date);
            if (holiday!=null)
            {
                return  holiday.Result;
            }
            HttpClient client = new HttpClient();
            var responseMessage = await client.GetAsync("http://api.tianapi.com/txapi/jiejiari/index?key=ee5572d19a68a276d0e5f6d2558f0876&date=" + date);
            var readStr = await responseMessage.Content.ReadAsStringAsync();
            if (!responseMessage.IsSuccessStatusCode)
                return readStr;
            
            //var result =_jsonSerializer.Deserialize<HolidayDto>(readStr);
            await _holidays.InsertAsync(new Holiday() { Result = readStr, Date = date });
            return readStr;
        }
    }
}
